package fr.mairie.parc.page.demande;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.click.ActionResult;
import org.apache.click.Context;
import org.apache.click.control.ActionLink;
import org.apache.click.control.FieldSet;
import org.apache.click.control.Form;
import org.apache.click.control.ImageSubmit;
import org.apache.click.control.Option;
import org.apache.click.control.Select;
import org.apache.click.dataprovider.DataProvider;
import org.apache.click.element.Element;
import org.apache.click.element.JsImport;
import org.apache.click.element.JsScript;
import org.apache.click.extras.control.IntegerField;
import org.apache.click.util.Bindable;
import org.apache.click.util.ClickUtils;
import org.springframework.context.ApplicationContext;

import fr.mairie.parc.context.AppContext;
import fr.mairie.parc.control.demande.DemandeFields;
import fr.mairie.parc.control.user.UserPanel;
import fr.mairie.parc.control.user.UserTable;
import fr.mairie.parc.domain.Demande;
import fr.mairie.parc.domain.User;
import fr.mairie.parc.page.BorderPage;
import fr.mairie.parc.service.DemandeManager;
import fr.mairie.parc.service.UserManager;

public class EditDemandePage extends BorderPage {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Resource protected DemandeManager demandeManager;
	@Resource protected UserManager userManager;
	@Bindable protected Form form = new Form();
	@Bindable protected Integer idDemande;
	@Bindable protected UserTable userResultTable = new UserTable("userResultTable", this, EditDemandePage.class);
	protected transient Demande demande;
	protected transient User user;

	@Bindable protected Form attform = new Form();
	private IntegerField idAttribution = new IntegerField ("idAttribution", "ID");
	private FieldSet fieldset = new FieldSet("attributionFieldset", "Attribution");
	private IntegerField idDemandeAtt = new IntegerField("idDemandeAtt", "idDemande");
	private IntegerField idUserAtt = new IntegerField("idUserAtt", "idUser");
	//private IntegerField idMaterielAtt = new IntegerField("idMaterielAtt", "idMateriel");

	private ActionLink selectLink = new ActionLink("selectLink", "Select", this, "onSelectClick");

	protected DemandeFields fields = new DemandeFields(false);

	@Bindable private Select userSelect = new Select ("userSelect");



	public EditDemandePage() {
		fields.addAll(form);

		attform.add(fieldset);
		fieldset.add(idAttribution);
		fieldset.add(idDemandeAtt);
		fieldset.add(idUserAtt);
		//fieldset.add(idMaterielAtt);

		addControl(userSelect);

		form.add(new ImageSubmit("OK", "/assets/images/32x32/accept.png", this,"onSubmit"));
		form.add(new ImageSubmit("Cancel", "/assets/images/32x32/cancel.png",this, "onCancelClicked"));
	}

	@SuppressWarnings({ "rawtypes", "serial" })
	@Override
	public void onInit() {
		super.onInit();
		ApplicationContext ctx = AppContext.getApplicationContext();
		demandeManager = (DemandeManager) ctx.getBean("demandeManager");
		userManager = (UserManager) ctx.getBean("userManager");
    	//materielManager = (MaterielManager) ctx.getBean("materielManager");

		userSelect.setDataProvider(new DataProvider() {

			@Override
			public List getData() {
				List<Option> optionList = new ArrayList<Option> ();
				List<User> userList = userManager.selectAll();
				for (User user : userList) {
					optionList.add(new Option(user.getIdUser(), user.getNom()));
				}
				return optionList;
			}
		});
	}

	@Override
	public void onRender() {
		if (idDemande < 0) {
			msg = "Error, invalid id:" + idDemande + " for Demande";
			setRedirect("error.htm");
			return;
		}
		if (demande == null) {
			demande =  demandeManager.getDemandeById(idDemande);

		}
		if (demande == null) {
			msg = "Error, Demande not found for id:" + idDemande;
			setRedirect("error.htm");
			return;
		}

		idDemandeAtt.setInteger(idDemande);

		fields.setFieldsValues(demande);
		//user = userManager.getUserbyName(fields.getUtilisateur().getValue());
		userResultTable.setDataProvider(new DataProvider<User>() {
			private static final long serialVersionUID = 1L;
			public Iterable<User> getData() {
				List<User> res = userManager.getUserbyName(fields.getUtilisateur().getValue());
		    	return res;
		    }
		});
		//ActionLink selectLink = new ActionLink("Select", this,"onSelectClick");
		selectLink.setImageSrc("/assets/images/16x16/application_form_edit.png");
		selectLink.setTitle("Selectionner un utilisateur");

		//validationRowLink.setParameter("referrer", "list-user-dif-request.htm");

		userResultTable.addActionColumnLink(selectLink);
		//demandeValidation.setFieldValues(demande);


		super.onRender();
	}

	public boolean onCancelClicked() {
        setRedirect(ListDemandePageOld.class);
        return false;
    }

	public boolean onSelectClick() {
        Integer id = selectLink.getValueInteger();
        idUserAtt.setInteger(id);
        return true;
    }

	@Override
    public List<Element> getHeadElements() {
        if (headElements == null) {
            headElements = super.getHeadElements();

            // Include the prototype.js library which is made available under
            // the web folder "/click/prototype/"
            headElements.add(new JsImport("/click/prototype/prototype.js"));

            Context context = getContext();

            // Create a model to pass to the Page JavaScript template. The
            // template recognizes the following Velocity variables:
            // $context, $path, $selector and $target
            Map<String, Object> model = ClickUtils.createTemplateModel(this, context);

            // Add a CSS selector, in this case the customerSelect ID attribute
            model.put("selector", userSelect.getId());

            // Add the ID of a target element in the Page template to replace
            // with new data, in this example the target is 'customerDetails'
            model.put("target", "userDetails");

            // Include the Page associated JavaScript template
            headElements.add(new JsScript("/ajax/select/edit-demande.js", model));
        }

        return headElements;
    }

	public ActionResult onClickUser() {
        ActionResult actionResult = new ActionResult();

        // Lookup customer based on request parameter 'customerId'
        //String userId = getContext().getRequest().getParameter("IdUser");
        String userId = getContext().getRequest().getParameter("userId");

        User user = userManager.getUserById(userId);

        // CustomerPanel will render the customer as an HTML snippet
        UserPanel userPanel = new UserPanel(this, user);
        actionResult.setContent(userPanel.toString());

        // Set content type and character encoding
        actionResult.setCharacterEncoding("UTF-8");
        actionResult.setContentType(ActionResult.HTML);

        return actionResult;
    }


}
